#include "gameitem.h"

#include "gameview.h"

#include <QPainter>
#include <QDebug>

GameItem::GameItem(GameView *parent) : QObject(parent) {
    setView(parent);
}

void GameItem::setPos(QPointF new_pos) {
    pos = new_pos;
}
QPointF GameItem::getPos() {
    return pos;
}
void GameItem::setSpeed(QPointF speed) {
    this->speed = speed;
}
QPointF GameItem::getSpeed() {
    return speed;
}
void GameItem::update(qreal interval_ms) {
    pos += speed * interval_ms;
}

void GameItem::setBoundingSize(QSizeF sizeF) {
    this->boundingSize = sizeF;
}

QSizeF GameItem::getBoundingSize() {
    return boundingSize;
}
QRectF GameItem::getBoundingRect() {
    return {pos, getBoundingSize()};
}
bool GameItem::collidesWithItem(GameItem *other) {
    return getBoundingRect().intersects(other->getBoundingRect());
}
GameView *GameItem::getView() {
    return view;
}
void GameItem::setView(GameView *view) {
    this->view = view;
}

void GamePixmapItem::paint(QPainter *painter) {
    painter->drawPixmap(getPos(), pixmap, pixmap_rectF);
}

GamePixmapItem::GamePixmapItem(const QPixmap &pixmap, GameView *parent) :pixmap(pixmap), GameItem(parent) {
    GameItem::setBoundingSize(pixmap.size());
    GamePixmapItem::setPixmapRectF(pixmap.rect());
}

void GamePixmapItem::setPixmapRectF(QRectF rectF) {
    pixmap_rectF = rectF;
}
QRectF GamePixmapItem::getPixmapRectF() {
    return pixmap_rectF;
}
void GamePixmapMovieItem::update(qreal interval_ms) {
    GameItem::update(interval_ms);
    if(state == Running) {
        interval_count += interval_ms;
        if (interval_count > interval) {
            interval_count -= interval;
            currentFrameIndex++;
        }
        if(currentFrameIndex >= pixSequence.size()){
            currentFrameIndex = pixSequence.size()-1;
            state = NotRunning;
            emit finished();
        }
    }
}
void GamePixmapMovieItem::paint(QPainter *painter) {
    painter->drawPixmap(getPos(), pixSequence[currentFrameIndex]);
}
GamePixmapMovieItem::GamePixmapMovieItem(QList<QPixmap> pixSequence, qreal time, GameView *view)
    : GameItem(view), pixSequence(std::move(pixSequence)) {
    interval = time/this->pixSequence.size();
    GamePixmapMovieItem::reset();
}
void GamePixmapMovieItem::start() {
    state = Running;
}
void GamePixmapMovieItem::pause() {
    state = Paused;
}
void GamePixmapMovieItem::reset() {
    state = NotRunning;
    interval_count = 0;
    currentFrameIndex = 0;
}
